package cn.xkai.exercise.c;

/**
 * @description: 颜色分类
 * @author: kaixiang
 * @date: 2022-07-28
 **/
public class Solution109 {
    public void sortColors(int[] nums) {
        int redIndex = 0;
        int blueIndex = nums.length - 1;

        // 把红色和蓝色放在两边，中间自然就是白色
        for (int i = 0; i < blueIndex + 1; i++) {
            if (nums[i] == 0) {
                int tmp = nums[redIndex];
                nums[redIndex++] = nums[i];
                nums[i] = tmp;
            } else if (nums[i] == 2) {
                int tmp = nums[blueIndex];
                nums[blueIndex--] = nums[i];
                nums[i] = tmp;
                // 避免遗漏
                i--;
            }
        }
    }
}
